{% extends 'base.html' %}
{% load static %}

{% block content %}
<div class="container mt-4">
    <h5>{{ student.name }} - {{ semester }}评语编辑 <i class="bi bi-pencil"></i></h5>
    <form id="comment-form" method="post">
        {% csrf_token %}
        <input type="hidden" name="student_id" value="{{ student.id }}">
        <input type="hidden" name="class_id" value="{{ class_info.id }}">
        <input type="hidden" name="semester_id" value="{{ semester.id }}">
        <div class="mb-3">
            <textarea id="comment-content" name="content" class="form-control" rows="10">{{ comment.content }}</textarea>
        </div>
        <div class="d-flex justify-content-between">
            <button type="button" id="generate-btn" class="btn btn-primary"><i class="bi bi-magic"></i> 生成评语</button>
            <button type="submit" class="btn btn-success"><i class="bi bi-save"></i> 保存评语</button>
        </div>
    </form>
</div>

<script>
    // 使用base.html中已引入的CKEditor
    CKEDITOR.replace('comment-content', {
        height: 400,
        language: 'zh-cn'
    });
    
    // 生成评语按钮点击事件
    document.getElementById('generate-btn').addEventListener('click', function() {
        if (confirm('确定要生成新的评语吗？当前内容将会被覆盖。')) {
            const studentId = document.querySelector('input[name="student_id"]').value;
            const classId = document.querySelector('input[name="class_id"]').value;
            const semesterId = document.querySelector('input[name="semester_id"]').value;

            fetch('/api/generate-comment/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-CSRFToken': document.querySelector('input[name="csrfmiddlewaretoken"]').value
                },
                body: `student_id=${studentId}&class_id=${classId}&semester_id=${semesterId}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    CKEDITOR.instances['comment-content'].setData(data.content);
                    alert('评语生成成功！');
                } else {
                    alert('生成失败: ' + data.error);
                }
            })
            .catch(error => {
                alert('生成过程中出错: ' + error);
            });
        }
    });
</script>
{% endblock %}